package com.immediatus.engine.layer;

import com.immediatus.engine.input.TouchEvent;
import com.immediatus.engine.shape.Shape;
import com.immediatus.graphics.camera.Camera;

import javax.microedition.khronos.opengles.GL10;

public class CameraCanvas extends Canvas{
    protected Camera _camera;

    public CameraCanvas(){
        this(null);
    }

    public CameraCanvas(final Camera camera_){
        this._camera = camera_;
    }

    public Camera getCamera(){
        return this._camera;
    }

    public void setCamera(final Camera camera_){
        this._camera = camera_;
    }

    @Override
    public boolean onTouchEvent(final TouchEvent event_){
        if (this._camera == null){
            return false;
        } else{
            this._camera.convertLayerToCameraTouchEvent(event_);

            final boolean handled = super.onTouchEvent(event_);

            if (handled){
                return true;
            } else{
                this._camera.convertCameraToLayerTouchEvent(event_);
                return false;
            }
        }
    }

    @Override
    protected boolean onChildTouchEvent(final TouchEvent event_){
        final boolean childIsCameraLayer = this.getChild() instanceof CameraCanvas;
        if (childIsCameraLayer){
            this._camera.convertCameraToLayerTouchEvent(event_);
            final boolean result = super.onChildTouchEvent(event_);
            this._camera.convertLayerToCameraTouchEvent(event_);
            return result;
        } else{
            return super.onChildTouchEvent(event_);
        }
    }

    @Override
    protected void onManagedDraw(final GL10 gl, final Camera camera){
        if (this._camera != null){
            gl.glMatrixMode(GL10.GL_PROJECTION);
            this._camera.onApplyCameraLayerMatrix(gl);
            {
                gl.glMatrixMode(GL10.GL_MODELVIEW);
                gl.glPushMatrix();
                gl.glLoadIdentity();

                super.onManagedDraw(gl, camera);

                gl.glPopMatrix();
            }
            gl.glMatrixMode(GL10.GL_PROJECTION);
        }
    }

    public void centerShapeInCamera(final Shape shape_){
        final Camera camera = this._camera;
        shape_.setPosition(
                (camera.getWidth() - shape_.getWidth()) * 0.5f, (camera.getHeight() - shape_.getHeight()) * 0.5f);
    }

    public void centerShapeInCameraHorizontally(final Shape shape_){
        shape_.setPosition((this._camera.getWidth() - shape_.getWidth()) * 0.5f, shape_.getY());
    }

    public void centerShapeInCameraVertically(final Shape shape_){
        shape_.setPosition(shape_.getX(), (this._camera.getHeight() - shape_.getHeight()) * 0.5f);
    }
}
